﻿Public Class FGenerateOpenMediaInfo
    Private mSharedItem As Entities.SharedItem

    Public Shared Sub ShowIt(ByVal sharedItem As Entities.SharedItem)
        Dim clsView As New FGenerateOpenMediaInfo
        clsView.Show(sharedItem)
    End Sub
    Public Shared Sub ShowIt()
        Dim clsView As New FGenerateOpenMediaInfo
        clsView.Show()
    End Sub
    Public Shared Sub ShowIt(ByVal files() As String)
        Dim clsView As New FGenerateOpenMediaInfo
        clsView.Show(files)
    End Sub


    Private Shadows Sub Show()
        Me.Text = "Generate Open Media Info..."
        Me.Icon = CommonResources.My.Resources.Buddy
        Show(New String() {})
        MyBase.Show()
    End Sub
    Private Shadows Sub Show(ByVal sharedItem As Entities.SharedItem)
        mSharedItem = sharedItem
        Dim aFiles As Generic.List(Of Entities.SharedItemFile)
        aFiles = DataStore.SharedItemsFiles.GetAllBySharedItemId(sharedItem.Id)
        Dim aFileNames As New Generic.List(Of String)
        For Each clsFile As Entities.SharedItemFile In aFiles
            aFileNames.Add(IO.Path.Combine(clsFile.Directory, clsFile.FileName))
        Next
        Show(aFileNames.ToArray)
    End Sub
    Private Shadows Sub Show(ByVal files() As String)
        Dim strTitle As String = Nothing
        For Each strFilename As String In files
            Select Case IO.Path.GetExtension(strFilename).ToLower
                Case ".mp4", ".avi", ".mkv"
                    strTitle = ExtractTitleFromFilename(strFilename)
                    Exit For
            End Select
        Next

        If strTitle IsNot Nothing Then
            Dim strSearchUrl As String = String.Format("http://www.imdb.com/find?s=tt&q={0}", strTitle.Replace(" "c, "+"c))
            WebBrowser1.Navigate(strSearchUrl)
        Else
            WebBrowser1.Navigate("http://www.imdb.com")
        End If

        If mSharedItem Is Nothing Then
            Me.Text = "Generate Open Media Info..."
        Else
            Me.Text = String.Format("Generate Open Media Info for item {0}", mSharedItem.Name)
        End If

        AddFiles(files)
        MyBase.Show()
    End Sub

    Private Function ExtractTitleFromFilename(ByVal fileName As String) As String
        Dim strFileName As String = IO.Path.GetFileNameWithoutExtension(fileName).Trim
        strFileName = strFileName.Replace("."c, " "c).Trim

        Dim iPos As Integer = strFileName.IndexOf("["c)
        While iPos > 0
            Dim iPos2 As Integer = strFileName.IndexOf("]"c, iPos + 1)
            strFileName = strFileName.Substring(0, iPos).Trim & strFileName.Substring(iPos2 + 1)
            iPos = strFileName.IndexOf("["c)
        End While

        iPos = strFileName.IndexOf("("c)
        While iPos > 0
            Dim iPos2 As Integer = strFileName.IndexOf(")"c, iPos + 1)
            strFileName = strFileName.Substring(0, iPos).Trim & strFileName.Substring(iPos2 + 1)
            iPos = strFileName.IndexOf("("c)
        End While

        If strFileName.ToLower.EndsWith(", the") Then
            strFileName = "The " & strFileName.Substring(0, strFileName.Length - 5)
        ElseIf strFileName.ToLower.EndsWith(", die") Then
            strFileName = "Die " & strFileName.Substring(0, strFileName.Length - 5)
        ElseIf strFileName.ToLower.EndsWith(", das") Then
            strFileName = "Das " & strFileName.Substring(0, strFileName.Length - 5)
        ElseIf strFileName.ToLower.EndsWith(", der") Then
            strFileName = "Der " & strFileName.Substring(0, strFileName.Length - 5)
        End If
        Return strFileName
    End Function

    Private Sub btnClearFiles_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClearFiles.Click
        lvwFiles.Items.Clear()
        ValidateFilesPage()
    End Sub

    Private Sub btnAddFiles_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddFiles.Click
        With OpenFileDialog1
            .Multiselect = True
            .Title = "Select files to add to Open Media Info..."
            .Filter = "Any media file|*.*"
            Select Case .ShowDialog(Me)
                Case Windows.Forms.DialogResult.OK
                    AddFiles(.FileNames)
            End Select
        End With
        ValidateFilesPage()
    End Sub
    Private Sub AddFiles(ByVal files() As String)
        lvwFiles.BeginUpdate()
        For Each strFilename As String In files
            Select Case IO.Path.GetExtension(strFilename).ToLower
                Case ".omx", ".nfo", ".txt"
                Case Else
                    With lvwFiles.Items.Add(IO.Path.GetFileName(strFilename))
                        .SubItems.Add(IO.Path.GetDirectoryName(strFilename))
                        .Tag = strFilename
                    End With
            End Select
        Next
        lvwFiles.EndUpdate()
    End Sub

    Private Function GetAllFiles() As Generic.List(Of String)
        Dim aFiles As New Generic.List(Of String)
        For Each clsItem As ListViewItem In lvwFiles.Items
            aFiles.Add(CStr(clsItem.Tag))
        Next
        Return aFiles
    End Function

    Private mMediaInfo As Entities.OpenMediaInfo.OpenMediaInfo

    Private Sub Wizard1_AfterSwitchPages(ByVal sender As Object, ByVal e As CristiPotlog.Controls.Wizard.AfterSwitchPagesEventArgs) Handles Wizard1.AfterSwitchPages
        If Wizard1.Pages(e.NewIndex) Is wpValidate Then
            mMediaInfo = OpenMediaInfo.Manager.GenerateForMovie(WebBrowser1.Url, GetAllFiles.ToArray)
            ShowMediaInfo(mMediaInfo)
        ElseIf Wizard1.Pages(e.NewIndex) Is wpImdbUrl Then
            ValidateImdbPage()
        ElseIf Wizard1.Pages(e.NewIndex) Is wpFiles Then
            ValidateFilesPage()
        End If
    End Sub

    Private Sub ShowMediaInfo(ByVal mediaInfo As Entities.OpenMediaInfo.OpenMediaInfo)
        RichTextBox1.Clear()
        lblTitle.Text = String.Empty
        picPoster.Image = Nothing
        If mediaInfo.Feature IsNot Nothing Then
            lblTitle.Text = mediaInfo.Feature.Title
            If mediaInfo.Feature.Poster IsNot Nothing Then
                Dim clsBitmap As System.Drawing.Bitmap
                Using clsStream As New IO.MemoryStream(mediaInfo.Feature.Poster.Data)
                    clsBitmap = New System.Drawing.Bitmap(clsStream)
                End Using
                picPoster.Image = clsBitmap
            End If

            Dim clsCaptionFont As New System.Drawing.Font("Arial", 12, Drawing.FontStyle.Bold Or Drawing.FontStyle.Underline, Drawing.GraphicsUnit.Point)
            Dim clsTextFont As New System.Drawing.Font("Arial", 10, Drawing.FontStyle.Regular, Drawing.GraphicsUnit.Point)

            RichTextBox1.SelectionFont = clsCaptionFont
            RichTextBox1.AppendText("Directors" & vbNewLine)
            For Each clsContr As Entities.OpenMediaInfo.Contributer In mediaInfo.Feature.Directors
                RichTextBox1.AppendText(vbTab)
                RichTextBox1.AppendText(clsContr.Name)
                RichTextBox1.AppendText(vbTab)
                If clsContr.Part IsNot Nothing Then RichTextBox1.AppendText(clsContr.Part)
                RichTextBox1.AppendText(vbNewLine)
            Next
            RichTextBox1.AppendText(vbNewLine)

            RichTextBox1.SelectionFont = clsCaptionFont
            RichTextBox1.AppendText("Writers" & vbNewLine)
            For Each clsContr As Entities.OpenMediaInfo.Contributer In mediaInfo.Feature.Writers
                RichTextBox1.AppendText(vbTab)
                RichTextBox1.AppendText(clsContr.Name)
                RichTextBox1.AppendText(vbTab)
                If clsContr.Part IsNot Nothing Then RichTextBox1.AppendText(clsContr.Part)
                RichTextBox1.AppendText(vbNewLine)
            Next
            RichTextBox1.AppendText(vbNewLine)

            RichTextBox1.SelectionFont = clsCaptionFont
            RichTextBox1.AppendText("Cast" & vbNewLine)
            For Each clsContr As Entities.OpenMediaInfo.Contributer In mediaInfo.Feature.Cast
                RichTextBox1.AppendText(vbTab)
                RichTextBox1.AppendText(clsContr.Name)
                RichTextBox1.AppendText(vbTab)
                If clsContr.Part IsNot Nothing Then RichTextBox1.AppendText(clsContr.Part)
                RichTextBox1.AppendText(vbNewLine)
            Next
            RichTextBox1.AppendText(vbNewLine)
        End If
    End Sub

    Private Sub Wizard1_BeforeSwitchPages(ByVal sender As Object, ByVal e As CristiPotlog.Controls.Wizard.BeforeSwitchPagesEventArgs) Handles Wizard1.BeforeSwitchPages
    End Sub

    Private Sub Wizard1_Finish(ByVal sender As Object, ByVal e As System.EventArgs) Handles Wizard1.Finish
        Dim strSaveAs As String

        If mSharedItem IsNot Nothing Then
            strSaveAs = Manager.GetSuggestedOMXFileName(mSharedItem, GetAllFiles.ToArray)
        Else
            SaveFileDialog1.Filter = "Open Media Info Xml File|*.omx"
            SaveFileDialog1.Title = String.Format("Save media info file for {0}", lblTitle.Text)

            Dim strDefaultFileName As String = GetAllFiles(0)
            SaveFileDialog1.InitialDirectory = IO.Path.GetDirectoryName(strDefaultFileName)
            SaveFileDialog1.FileName = IO.Path.GetFileNameWithoutExtension(strDefaultFileName) & ".omx"

            SaveFileDialog1.CheckFileExists = False
            SaveFileDialog1.OverwritePrompt = True
            Select Case SaveFileDialog1.ShowDialog(Me)
                Case Windows.Forms.DialogResult.OK
                    strSaveAs = SaveFileDialog1.FileName
                Case Else
                    strSaveAs = Nothing
            End Select
        End If

        If strSaveAs IsNot Nothing Then
            Dim strXml As String = Utils.Serialization.ToXml(mMediaInfo)
            Utils.IO.SaveTextFileUnicode(strSaveAs, strXml)
        End If
    End Sub

    Private Sub WebBrowser1_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
        ValidateImdbPage()
    End Sub

    Private Sub ValidateImdbPage()
        If WebBrowser1.Url.ToString.ToLower.IndexOf("imdb.com/title/tt") >= 0 Then
            Wizard1.NextEnabled = True
        Else
            Wizard1.NextEnabled = False
        End If
    End Sub
    Private Sub ValidateFilesPage()
        If lvwFiles.Items.Count > 0 Then
            Wizard1.NextEnabled = True
        Else
            Wizard1.NextEnabled = False
        End If
    End Sub
End Class